using System.Collections.Generic;
using Unity.Collections;
using UnityEngine;
using UnityEngine.ParticleSystemJobs;

public class ParticleTextures : MonoBehaviour
{
    [SerializeField] private ParticleSystem _ps;

    private List<TextureDisplayData> _displayData = new List<TextureDisplayData>();

    UpdateParticlesIconJob _job = new UpdateParticlesIconJob();

    private void Start()
    {
        if (_ps == null)
        {
            _ps = GetComponent<ParticleSystem>();
        }
        var customData = _ps.customData;
        customData.enabled = true;
        customData.SetMode(ParticleSystemCustomData.Custom1, UnityEngine.ParticleSystemCustomDataMode.Vector);
    }

    void Update()
    {
        if (_displayData.Count > 0)
        {
            var customData = _ps.customData;
            customData.enabled = true;


            _job.displayData = _displayData.ToNativeArray(Allocator.TempJob);
            _ps.Emit(_displayData.Count);
            _job.Schedule(_ps).Complete();
            _job.displayData.Dispose();
            _displayData.Clear();
            customData.enabled = false;
        }

    }
    //void OnParticleUpdateJobScheduled()
    //{
    //        _job.Schedule(_ps);
    //}

    public void Emit(TextureDisplayData data)
    {
        _displayData.Add(data);
    }
    //使用新产生的粒子,并修改值
    struct UpdateParticlesIconJob : IJobParticleSystem
    {
        [ReadOnly]
        public NativeArray<TextureDisplayData> displayData;
        public void Execute(ParticleSystemJobData particles)
        {
            var positionsX = particles.positions.x;
            var positionsY = particles.positions.y;
            var positionsZ = particles.positions.z;
            var textureIndex = particles.customData1.x;
            int particleIdx = particles.count - 1;
            for (int i = 0; i < displayData.Length; i++)
            {
                var data = displayData[i];
                positionsX[particleIdx] = data.Position.x;
                positionsY[particleIdx] = data.Position.y;
                positionsZ[particleIdx] = data.Position.z;

                textureIndex[particleIdx] = data.Type;
                particleIdx--;
            }

        }
    }

}

